﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using UnityEngine;

public class FrameExecuteTimeMonitor : MonoBehaviour
{
    private Stopwatch stopwatch = new Stopwatch();

    private static Queue<Action> taskQueue = new Queue<Action>();

    private static GameObject rootObject;
    
    public static void AddTask(Action action)
    {
        if (rootObject == null)
        {
            rootObject = new GameObject("FrameExecuteTimeMonitor");
            rootObject.AddComponent<FrameExecuteTimeMonitor>();
        }
        taskQueue.Enqueue(action);
    }

    
    private void Update()
    {
        stopwatch.Reset();
        stopwatch.Start();
    }

    private void LateUpdate()
    {
        long limitedMillisecond = 16;
        var frameRate = Application.targetFrameRate;
        if (frameRate >= 0)
        {
            limitedMillisecond = 1000 / frameRate;
        }
        //保证无论多低帧率，至少能执行一个任务
        long elapsed = 0;//stopwatch.ElapsedMilliseconds;
        while (elapsed < limitedMillisecond && taskQueue.Count > 0)
        {
            var task = taskQueue.Dequeue();
            task();
            elapsed = stopwatch.ElapsedMilliseconds;
        }
        stopwatch.Stop();
    }
}